package com.think.common.exception;

import com.think.common.utils.ResultUtil;
import com.think.common.utils.SysUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * <p>
 * 全局的的异常处理器
 * </p>
 *
 * @author: xwj
 * @data: 2019-04-21
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public HttpEntity handle(Exception e) {
        log.error("全局异常信息 ex={}", e.getMessage(), e);
        return ResultUtil.error(HttpStatus.INTERNAL_SERVER_ERROR, e.getMessage());
    }

    @ExceptionHandler(SysException.class)
    public HttpEntity exception(SysException e) {
        return ResultUtil.error(HttpStatus.INTERNAL_SERVER_ERROR, e.getMessage());
    }

    @ExceptionHandler(HttpMessageNotReadableException.class)
    public HttpEntity httpMessageNotReadableException() {
        return ResultUtil.error(HttpStatus.NOT_FOUND, "错误，参数格式不正确");
    }

    @ExceptionHandler(DataIntegrityViolationException.class)
    public HttpEntity DataIntegrityViolationException() {
        return ResultUtil.error(HttpStatus.NOT_FOUND, "错误，录入信息不正确");
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public HttpEntity methodArgumentNotValidException(MethodArgumentNotValidException ex) {
        return ResultUtil.error(HttpStatus.BAD_REQUEST, "错误，参数无效：" + buildMessages(ex.getBindingResult()));
    }

    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public HttpEntity httpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException ex) {
        return ResultUtil.error(HttpStatus.BAD_REQUEST, "错误，请求方法不支持");
    }

    /**
     * 获取校验失败的字段信息
     *
     * @param result
     * @return java.lang.String
     * @author xwj
     * @data 2019/4/22
     */
    private String buildMessages(BindingResult result) {
        // 声明字符对象
        StringBuilder resultBuilder = new StringBuilder();

        // 非空判断
        if (SysUtils.isEmpty(result)) {
            return resultBuilder.toString();
        }

        // 解析，返回
        result.getAllErrors().stream()
                .filter(error -> SysUtils.isNotEmpty(error) && error instanceof FieldError)
                .forEach(error -> {
                    FieldError fieldError = (FieldError) error;
                    String fieldName = fieldError.getField();
                    String fieldErrMsg = fieldError.getDefaultMessage();
                    resultBuilder.append(fieldName).append("，字段规则为【").append(fieldErrMsg).append("】；");
                });
        return resultBuilder.toString();
    }
}
